package com.bio.service.news.impl;

import java.io.Serializable;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.bio.dao.news.NewsDao;
import com.bio.entity.attachemnt.Attachment;
import com.bio.entity.news.News;
import com.bio.exception.OperationException;
import com.bio.service.attachment.AttachmentService;
import com.bio.service.impl.AbstractService;
import com.bio.service.news.NewsService;
import com.bio.utils.Environment;

public class NewsServiceImpl extends AbstractService<News, NewsDao> implements NewsService{

	public NewsServiceImpl(NewsDao dao) {
		super(dao);
	}

    private AttachmentService attachmentService;

    @Override
	public News save(News news) throws OperationException {
		Long userId = Environment.Session.getUserId();
		String userName = Environment.Session.getUserName();
		List<Attachment> attachments = news.getAttachments();
		if(null != news){
			news.setPublisherId(userId);
			news.setPublisherName(userName);
			
			String jsonString = attachmentService.batchProcess(attachments, news.getAttachmentsInfo(), news.getToDeletePics());
			news.setAttachmentsInfo(jsonString);
			news = super.save(news);
		}
		return news;
	}

	@Override
	public News get(Serializable id) {
		News news = super.get(id);
		if(null != news && StringUtils.isNotEmpty(news.getAttachmentsInfo())){
			JSONArray jArray = JSONArray.fromObject(news.getAttachmentsInfo());
			news.setAttachJSON(JSONArray.toList(jArray, JSONObject.class));
		}
		return news;
	}
    
	public AttachmentService getAttachmentService() {
		return attachmentService;
	}

	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}
}
